package com.lzx.adx.report.controller.v1.aqy;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.model.aqy.AqyRequest;
import com.lzx.adx.report.service.BackDataService;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.biz.product.CzChannelHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RequestMapping("/aqy/cz")
@RestController
@Slf4j
public class AqyCzController {


    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;

    public static final   String apiDesc="爱奇艺-创智";




    @GetMapping("/report")
    public ResponseEntity report(AqyRequest aqyRequest, HttpServletRequest request){

        //1.收到监测的数据存储
        ReportDTO reportDTO=reportMapper.toReportDTO(aqyRequest);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(aqyRequest));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis()/1000));
        reportDTO.setImeiSum(aqyRequest.getImei());
        reportDTO.setImei("");
        reportDTO.setOaidSum(aqyRequest.getOaidSum());
        reportExecutor.execute(()->{
            reportService.saveData(reportDTO);
        });

        AccountDTO accountDTO = AccountLocalCache.getInstance().get(aqyRequest.getDspId());

        String finalUrl= CzChannelHelper.covertCzReport(accountDTO,reportDTO);

        String body = HttpUtil.createGet(finalUrl).execute().body();

        return ResponseEntity.ok(new Result());

    }




    @GetMapping("callback")
    public ResponseEntity callBackUrl(String requestId,String tnaEvent) throws Exception {
        Map<String,Object> params=new HashMap<>();
        params.put("bizRequestId",requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if(CollectionUtil.isNotEmpty(list)){
            reportDTO = list.get(0);
            reportDTO.setResultType(tnaEvent);
            reportDTO.setResultTime(String.valueOf(System.currentTimeMillis()));
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,tnaEvent);
        }else{
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }



        //2.从缓存加载配置
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());

        String callback = reportDTO.getCallback();
        String decodeUrl = URLUtil.decode(callback, StandardCharsets.UTF_8);
        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);

        String eventType = jsonObject.getString("event_type");
        String finalResultUrl=decodeUrl+"&event_type="+eventType;
        HttpRequest body = HttpUtil.createGet(finalResultUrl);
        String result = body.execute().body();



        return ResponseEntity.ok(new Result());
    }

}
